package com.info.zhiduoduo.weixin.service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.system.UserType;
import com.info.zhiduoduo.common.constants.project.CompanyProjectState;
import com.info.zhiduoduo.common.constants.project.LongTermProjectState;
import com.info.zhiduoduo.common.constants.project.ProjectType;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.NumberUtil;
import com.info.zhiduoduo.core.formbean.CheckLongTermSubProjectFormBean;
import com.info.zhiduoduo.core.service.CommonService;
import com.info.zhiduoduo.core.service.CoreBrokerageService;
import com.info.zhiduoduo.core.service.CoreLongTermProjectService;
import com.info.zhiduoduo.core.service.WxMessageService;
import com.info.zhiduoduo.core.service.ZhiduoduoProjectService;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.repository.dto.maker.MakerDetailDto;
import com.info.zhiduoduo.repository.dto.project.LongProjectBriefDto;
import com.info.zhiduoduo.repository.dto.project.LongProjectDto;
import com.info.zhiduoduo.repository.dto.project.ProjectBriefDto;
import com.info.zhiduoduo.repository.entity.company.Company;
import com.info.zhiduoduo.repository.entity.company.CompanyAccount;
import com.info.zhiduoduo.repository.entity.company.CompanyProject;
import com.info.zhiduoduo.repository.entity.company.LongTermProject;
import com.info.zhiduoduo.repository.entity.order.TradeRecord;
import com.info.zhiduoduo.repository.entity.system.SystemProjectcategory;
import com.info.zhiduoduo.repository.mapper.company.CompanyProjectMapper;
import com.info.zhiduoduo.repository.mapper.company.LongTermProjectMapper;
import com.info.zhiduoduo.repository.mapper.system.ProjectCategoryMapper;
import com.info.zhiduoduo.weixin.formbean.project.ListSubProjectFormBean;
import com.info.zhiduoduo.weixin.formbean.project.LongProjectListFormBean;
import com.info.zhiduoduo.weixin.formbean.project.SubmitLongTermSubProjectFormBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

@Service
public class LongProjectService extends BaseService {

    @Autowired
    MakerService makerService;
    @Autowired
    ZhiduoduoProjectService zhiduoduoProjectService;
    @Autowired
    CoreLongTermProjectService coreLongTermProjectService;
    @Autowired
    CoreBrokerageService coreBrokerageService;
    @Autowired
    WxMessageService wxMessageService;
    @Autowired
    CommonService commonService;

    @Resource
    private LongTermProjectMapper longTermProjectMapper;
    @Resource
    private ProjectCategoryMapper projectCategoryMapper;
    @Resource
    private CompanyProjectMapper companyProjectMapper;


    /**
     * 获取项目详情
     */
    public SmartResult<LongProjectDto> getProjectDetail(BaseSimpleFormBean<Integer> formBean) {

        Integer projectid = formBean.getReqdata();
        if (projectid == null || projectid <= 0) return errorParamSmartResult();
        LongProjectDto longProjectDetail = longTermProjectMapper.getLongProjectDetail(projectid);
        //项目剩余天数
        Date now = new Date();
        if (longProjectDetail.getStartTime() != null) {
            int leftDays = DateUtil.getIntervalDays(now, longProjectDetail.getExpireDate());
            longProjectDetail.setLeftDays(leftDays);
        }
        //项目分类名
        SystemProjectcategory parentCategory = projectCategoryMapper.getParentCategory(longProjectDetail.getCategoryid());
        if (parentCategory != null) {
            longProjectDetail.setCategoryname(parentCategory.getProjectcategory());
        }
        //项目支付状态
        TradeRecord tradeRecord = getCompanyPayUserAmountTradeRecord(projectid);
        if (tradeRecord != null) {
            longProjectDetail.setTradeid(tradeRecord.getTradeid()).setTradestate(tradeRecord.getTradestate()).setRepay(tradeRecord.getRepay());
        }
        return smartResult(longProjectDetail);
    }

    public TradeRecord getCompanyPayUserAmountTradeRecord(int projectid) {
        return new TradeRecord().selectOne(Condition.create()
                .eq("projectid", projectid)
                .eq("business_type", Constants.KLT_PAY_BUSINESS_TYPE_USER_AMOUNT)
                .orderBy("tradeid", false)
                .last("limit 1"));
    }
    public TradeRecord getCompanyPayJiugeChargeTradeRecord(int projectid) {
        return new TradeRecord().selectOne(Condition.create()
                .eq("projectid", projectid)
                .eq("business_type", Constants.KLT_PAY_BUSINESS_TYPE_JIUGE_CHARGE)
                .orderBy("tradeid", false)
                .last("limit 1"));
    }


    /**
     * 获取长期项目列表
     */
    public SmartResult<ProjectBriefDto> getProjectList(BaseSimpleFormBean<LongProjectListFormBean> formBean) {

        LongProjectListFormBean reqdata = formBean.getReqdata();
        if (reqdata == null) return errorParamSmartResult();

        int id = formBean.getUserid();
        String name = reqdata.getName();
        int state = reqdata.getState();
        Date startDate = reqdata.getStartDate();
        Date endDate = reqdata.getEndDate();
        int categoryid = reqdata.getCategoryid();

        int compid = 0;
        int userid = 0;
        if (formBean.getIdtype() == UserType.MAKER) {
            userid = id;
        } else if (formBean.getIdtype() == UserType.COMPANY) {
            compid = id;
        }

        if (startDate == null) startDate = new Date((0));
        if (endDate == null) endDate = new Date();

        Page<ProjectBriefDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
        List<LongProjectBriefDto> list = longTermProjectMapper.getProjectBriefListByCompid(compid, userid, name, categoryid, state, startDate, endDate);

        //项目剩余天数
        Date now = new Date();
        list.forEach(p -> {
            Date expireDate = p.getExpireDate();
            if (p.getProjectstart() != null && p.getState() != 3) {
                p.setLeftDays(DateUtil.getIntervalDays(now, expireDate));
            }
        });

        return smartResultPage(page);
    }

    public SmartResult userSubmitLongTermSubProject(BaseSimpleFormBean<SubmitLongTermSubProjectFormBean> formBean) {
        int userid = formBean.getUserid();
        @Valid SubmitLongTermSubProjectFormBean reqdata = formBean.getReqdata();
        int parentProjectid = reqdata.getParentProjectid();
        BigDecimal amount = reqdata.getAmount();
        String remark = reqdata.getRemark();
        String attachmentUrl = reqdata.getAttachmentUrl();

        MakerDetailDto userInfo = makerService.getUserInfo(userid);
        Asserts.notNull(userInfo);

        LongTermProject longTermProject = new LongTermProject().selectById(parentProjectid);
        Asserts.notNull(longTermProject, StatusMsg.StatusMsg_347);
        Asserts.notTrue(NumberUtil.equals(longTermProject.getState(), LongTermProjectState.CREATED), StatusMsg.StatusMsg_348);
        Integer compid = longTermProject.getCompid();

        // 检查长期项目的有效期
        Asserts.isTrue(coreLongTermProjectService.checkValid(longTermProject), StatusMsg.StatusMsg_348);
        // 检查是否有验收中的项目
        int checkingCount = new CompanyProject().selectCount(Condition.create()
                .eq("type", ProjectType.LONG_TERM)
                .eq("parent_projectid", parentProjectid)
                .eq("state", CompanyProjectState.CHECKING));
        Asserts.equalZero(checkingCount, StatusMsg.StatusMsg_351);
        // 检查长期项目总金额是否超过
        coreLongTermProjectService.checkTotalAmount(longTermProject, amount);

        Company company = new Company().selectOne(Condition.create().eq("compid", compid));
        CompanyProject project = new CompanyProject().setCompid(compid)
                .setCompname(company.getCompname())
                .setProjectname(longTermProject.getProjectname())
                .setUserid(longTermProject.getUserid())
		        .setUsername(userInfo.getUsername())
                .setRealname(userInfo.getRealname())
                .setCategoryid(longTermProject.getCategoryid())
                .setType(ProjectType.LONG_TERM)
                .setParentProjectid(longTermProject.getProjectid())
                .setProjecttype(longTermProject.getProjecttype())
                .setProjectintro(longTermProject.getProjectintro())
                .setInvoicetype(longTermProject.getInvoicetype())
                .setInvoicecontent(longTermProject.getInvoicecontent())
                .setProjectamount(amount)
                .setProjectsubmit(new Date())
                .setProjectstart(new Date())
                .setProjectcheckstart(new Date())
                .setAttachmentUrl(attachmentUrl)
                .setAutoCheck(0)
                .setPayId(longTermProject.getPayId())
                .setPartyId(longTermProject.getPartyId())
                .setState(CompanyProjectState.CHECKING)
                .setLongTermProjectRemark(remark);
        if (project.insert()) {
            // 新建合伙人分佣
            coreBrokerageService.prepareProjectBrokerage(compid, project.getUserid(), project.getProjectid(), ProjectType.LONG_TERM);
            // 通知企业
            wxMessageService.notifyCompanyProjectCheck(project.getProjectid());
        }
        return SmartResult.success();
    }

    public SmartResult companyCheckLongTermSubProject(BaseSimpleFormBean<CheckLongTermSubProjectFormBean> formBean) {
        return zhiduoduoProjectService.checkLongTermProject(formBean.getReqdata());
    }

    public SmartResult<ProjectBriefDto> listSubProjects(BaseSimpleFormBean<ListSubProjectFormBean> formBean) {
        @Valid ListSubProjectFormBean reqdata = formBean.getReqdata();
        Page<ProjectBriefDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
        companyProjectMapper.listLongTermSubProjects(reqdata.getParentProjectid(), reqdata.getState(), reqdata.getWhetherUploadFile());
        return SmartResult.ofPage(page);
    }
}
